const errorType = require("../constants/error-types");
const service = require("../service/user.service");
const md5Password = require("../utils/password-handler");

// 判断用户是否已存在的中间件
const verifyUser = async (ctx, next) => {
	const { name } = ctx.request.body;
	const result = await service.getUserByName(name);
	if (result.length) {
		const error = new Error(errorType.USER_ALREADY_EXISTS);
		return ctx.app.emit("error", error, ctx);
	}

	await next();
};

// 密码加密的中间件
const handlePassword = async (ctx, next) => {
	//   获取密码
	let { password } = ctx.request.body;
	// 加密
	ctx.request.body.password = md5Password(password);

	await next();
};

module.exports = {
	verifyUser,
	handlePassword
};
